/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rubric;

import com.jtattoo.plaf.acryl.AcrylLookAndFeel;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Properties;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.yaml.snakeyaml.error.YAMLException;
import specifications.Directive;
import specifications.Parameter;
import specifications.Specifications;

/**
 *
 * @author Jason
 */
public class Main extends javax.swing.JFrame {

    public static Boolean saved;
    private String location;
    private FileFilter ff;
    private Rubric rubric;
    public static ScorePane score;
    
    /**
     * Creates new form Main
     */
    public Main() {
        rubric = new Rubric();
        ff = new FileNameExtensionFilter("Specifications File (*.yml)", "yml", "yaml", "ysp");
        initComponents();
        score = new ScorePane(rubric);
        scoring.setViewportView(score);
        saved = true;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        target = new javax.swing.JScrollPane();
        notLoadedPanel2 = new rubric.NotLoadedPanel();
        production = new javax.swing.JScrollPane();
        notLoadedPanel1 = new rubric.NotLoadedPanel();
        environment = new javax.swing.JScrollPane();
        notLoadedPanel3 = new rubric.NotLoadedPanel();
        relationships = new javax.swing.JScrollPane();
        notLoadedPanel4 = new rubric.NotLoadedPanel();
        scoring = new javax.swing.JScrollPane();
        menu = new javax.swing.JMenuBar();
        file = new javax.swing.JMenu();
        save = new javax.swing.JMenuItem();
        saveAs = new javax.swing.JMenuItem();
        load = new javax.swing.JMenuItem();
        exit = new javax.swing.JMenuItem();
        help = new javax.swing.JMenu();
        specsHelp = new javax.swing.JMenuItem();
        rubricHelp = new javax.swing.JMenuItem();
        about = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Rubric Viewer");
        setResizable(false);

        target.setViewportView(notLoadedPanel2);

        jTabbedPane1.addTab("Target", target);

        production.setViewportView(notLoadedPanel1);

        jTabbedPane1.addTab("Production", production);

        environment.setViewportView(notLoadedPanel3);

        jTabbedPane1.addTab("Environment", environment);

        relationships.setViewportView(notLoadedPanel4);

        jTabbedPane1.addTab("Relationships", relationships);
        jTabbedPane1.addTab("Scoring", scoring);

        file.setText("File");

        save.setText("Save");
        save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveActionPerformed(evt);
            }
        });
        file.add(save);

        saveAs.setText("Save as");
        saveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveAsActionPerformed(evt);
            }
        });
        file.add(saveAs);

        load.setText("Load");
        load.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadActionPerformed(evt);
            }
        });
        file.add(load);

        exit.setText("Exit");
        exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitActionPerformed(evt);
            }
        });
        file.add(exit);

        menu.add(file);

        help.setText("Help");

        specsHelp.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK));
        specsHelp.setText("Specifications");
        help.add(specsHelp);

        rubricHelp.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.ALT_MASK));
        rubricHelp.setText("Rubric");
        help.add(rubricHelp);

        about.setText("About");
        help.add(about);

        menu.add(help);

        setJMenuBar(menu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
        saveRubric();
    }//GEN-LAST:event_saveActionPerformed

    private void saveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAsActionPerformed
        JFileChooser fc = new JFileChooser(location);
        fc.addChoosableFileFilter(ff);
        fc.setFileFilter(ff);
        int selected = fc.showSaveDialog(this);
        if (selected == JFileChooser.APPROVE_OPTION) {
            File outfile = fc.getSelectedFile();
            location = outfile.getAbsolutePath();
            if (!location.endsWith(".yml") && !location.endsWith(".yaml") && !location.endsWith(".ysp")) {
                location = location + ".yml";
            }
            try {
                rubric.dump(location);
                saved = true;
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "Unable to save file!");
            }
        } else {
            //do nothing
        }
    }//GEN-LAST:event_saveAsActionPerformed

    private void loadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadActionPerformed
        loadRubric();
    }//GEN-LAST:event_loadActionPerformed

    private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
        if (saved) {
            System.exit(0);
        } else {
            int tosave = JOptionPane.showConfirmDialog(this, "Save rubric?");
            if (tosave == JOptionPane.YES_OPTION) {
                saveRubric();
                if (saved) {
                    System.exit(0);
                }
            } else if (tosave == JOptionPane.NO_OPTION) {
                System.exit(0);
            } else {
                //do nothing
            }
        }
    }//GEN-LAST:event_exitActionPerformed

    public void loadRubric() {
        if (saved) {
            //attempt to load specs/rubric
            JFileChooser fc = new JFileChooser(location);
            fc.addChoosableFileFilter(ff);
            fc.setFileFilter(ff);
            int selected = fc.showOpenDialog(this);
            if (selected == JFileChooser.APPROVE_OPTION) {
                File infile = fc.getSelectedFile();
                location = infile.getAbsolutePath();
                rubric = new Rubric();
                try {
                    try {
                        rubric = rubric.load(location);
                        rubric.setGraded(true);
                    } catch (YAMLException ex) {
                        rubric = new Rubric(new Specifications().load(location));
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Unable to load file!");
                    return;
                }
            } else {
                return; //return without loading or checking anything more
            }

        } else {
            int tosave = JOptionPane.showConfirmDialog(this, "Save current specifications?");
            if (tosave == JOptionPane.YES_OPTION) {
                saveRubric();
                if (saved) {
                    //attempt to load specs
                    JFileChooser fc = new JFileChooser(location);
                    fc.addChoosableFileFilter(ff);
                    fc.setFileFilter(ff);
                    int selected = fc.showOpenDialog(this);
                    if (selected == JFileChooser.APPROVE_OPTION) {
                        File infile = fc.getSelectedFile();
                        location = infile.getAbsolutePath();
                        rubric = new Rubric();
                        try {
                            try {
                                rubric = rubric.load(location);
                                rubric.setGraded(true);
                            } catch (YAMLException ex) {
                                rubric = new Rubric(new Specifications().load(location));
                            }
                        } catch (Exception ex) {
                            JOptionPane.showMessageDialog(this, "Unable to load file!");
                            return;
                        }
                    } else {
                        return; //return without loading or checking anything more
                    }
                }
            } else if (tosave == JOptionPane.NO_OPTION) {
                //attempt to load specs
                JFileChooser fc = new JFileChooser(location);
                fc.addChoosableFileFilter(ff);
                fc.setFileFilter(ff);
                int selected = fc.showOpenDialog(this);
                if (selected == JFileChooser.APPROVE_OPTION) {
                    File infile = fc.getSelectedFile();
                    location = infile.getAbsolutePath();
                    rubric = new Rubric();
                    try {
                        try {
                            rubric = rubric.load(location);
                            rubric.setGraded(true);
                        } catch (YAMLException ex) {
                            rubric = new Rubric(new Specifications().load(location));
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this, "Unable to load file!");
                        return;
                    }
                } else {
                    return; //return without loading or checking anything more
                }
            } else {
                return; //return without loading or checking anything more
            }
        }

        //RubricPanel sourcePane = new RubricPanel();
        RubricPanel targetPane = new RubricPanel("This panel represents the instructions given to the post-editor about how the final target text should be rendered. Please indicate whether you feel that the target text meets each requirement. If you are unsure, select no.");
        RubricPanel prodPane = new RubricPanel("This panel represents the instructions given to the post-editor about what steps they should take in correcting the raw machine translation. Please indicate whether you feel that the post-editor followed each requirement based on the scenario and taget text. If you are unsure, select no.");
        RubricPanel environPane = new RubricPanel("This panel represents the instructions given to the post-editor about what technology they must use in order to provide a quality translation. It also lists requirements about the post-editor's location and whether the post-editor may share the work with a third party. Please indicate whether you feel that whether you feel that the post-editor followed each requirement based on the scenario and taget text. If you are unsure, select no.");
        RubricPanel relationPane = new RubricPanel("This panel represents the instructions given to the post-editor about the delivery and use of the translation materials. Please indicate whether you feel that the post-editor met each requirement based on the scenario and taget text. If you are unsure, select no.");

        //source.setViewportView(sourcePane);
        target.setViewportView(targetPane);
        production.setViewportView(prodPane);
        environment.setViewportView(environPane);
        relationships.setViewportView(relationPane);

//        LinkedHashMap<String, Parameter> sourceMap = rubric.getSpecifications().getCategory(Specifications.SOURCE);
//        ArrayList<RubricDirectivePanel> sourceList = new ArrayList<RubricDirectivePanel>();
//        for (Parameter p : sourceMap.values()) {
//            for (Directive d : p.getDirectives()) {
//                sourceList.add(new RubricDirectivePanel(new ScoredDirective(d)));
//            }
//        }
//        RubricDirectivePanel[] sourceDirectives = sourceList.toArray(new RubricDirectivePanel[]{});
//        sourcePane.setDirectives(sourceDirectives);
        Boolean crap = rubric.getGraded();
        if (crap) {
        targetPane.setDirectives(rubric.getTargetDirectives());
        prodPane.setDirectives(rubric.getProductionDirectives());
        environPane.setDirectives(rubric.getEnvironmentDirectives());
        relationPane.setDirectives(rubric.getRelationshipsDirectives());
        
        } else {
        LinkedHashMap<String, Parameter> targetMap = rubric.getSpecifications().getCategory(Specifications.TARGET);
        ArrayList<ScoredDirective> targetList = new ArrayList<ScoredDirective>();
        for (Parameter p : targetMap.values()) {
            for (Directive d : p.getDirectives()) {
                targetList.add(0, new ScoredDirective(d));
            }
        }
        rubric.setTargetDirectives(targetList);
        targetPane.setDirectives(targetList);

        LinkedHashMap<String, Parameter> prodMap = rubric.getSpecifications().getCategory(Specifications.PRODUCTION);
        ArrayList<ScoredDirective> prodList = new ArrayList<ScoredDirective>();
        for (Parameter p : prodMap.values()) {
            for (Directive d : p.getDirectives()) {
                prodList.add(0, new ScoredDirective(d));
            }
        }
        rubric.setProductionDirectives(prodList);
        prodPane.setDirectives(prodList);

        LinkedHashMap<String, Parameter> environMap = rubric.getSpecifications().getCategory(Specifications.ENVIRONMENT);
        ArrayList<ScoredDirective> environList = new ArrayList<ScoredDirective>();
        for (Parameter p : environMap.values()) {
            for (Directive d : p.getDirectives()) {
                environList.add(0, new ScoredDirective(d));
            }
        }
        rubric.setEnvironmentDirectives(environList);
        environPane.setDirectives(environList);

        LinkedHashMap<String, Parameter> relationMap = rubric.getSpecifications().getCategory(Specifications.RELATIONSHIPS);
        ArrayList<ScoredDirective> relationList = new ArrayList<ScoredDirective>();
        for (Parameter p : relationMap.values()) {
            for (Directive d : p.getDirectives()) {
                relationList.add(0, new ScoredDirective(d));
            }
        }
        rubric.setRelationshipsDirectives(relationList);
        relationPane.setDirectives(relationList);
        }
        
        score = new ScorePane(rubric);
        score.updateScore();
        scoring.setViewportView(score);
        this.validate();
        rubric.setGraded(true);
        saved = true;
    }

    public void saveRubric() {
        if (location == null) {
            JFileChooser fc = new JFileChooser(location);
            fc.addChoosableFileFilter(ff);
            fc.setFileFilter(ff);
            int selected = fc.showSaveDialog(this);
            if (selected == JFileChooser.APPROVE_OPTION) {
                File outfile = fc.getSelectedFile();
                location = outfile.getAbsolutePath();
            } else {
                return; //return without saving
            }
        }
        if (!location.endsWith(".yml") && !location.endsWith(".yaml") && !location.endsWith(".ysp")) {
            location = location + ".yml";
        }
        try {
            rubric.dump(location);
            saved = true;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Unable to save file!");
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                //System.out.println(info.getName());
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
            }
            Properties props = new Properties();
            props.put("logoString", "Ruqual");
            AcrylLookAndFeel.setCurrentTheme(props);
            javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel");
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(rubric.Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(rubric.Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(rubric.Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(rubric.Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem about;
    private javax.swing.JScrollPane environment;
    private javax.swing.JMenuItem exit;
    private javax.swing.JMenu file;
    private javax.swing.JMenu help;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JMenuItem load;
    private javax.swing.JMenuBar menu;
    private rubric.NotLoadedPanel notLoadedPanel1;
    private rubric.NotLoadedPanel notLoadedPanel2;
    private rubric.NotLoadedPanel notLoadedPanel3;
    private rubric.NotLoadedPanel notLoadedPanel4;
    private javax.swing.JScrollPane production;
    private javax.swing.JScrollPane relationships;
    private javax.swing.JMenuItem rubricHelp;
    private javax.swing.JMenuItem save;
    private javax.swing.JMenuItem saveAs;
    private javax.swing.JScrollPane scoring;
    private javax.swing.JMenuItem specsHelp;
    private javax.swing.JScrollPane target;
    // End of variables declaration//GEN-END:variables

}
